
package com.songbl.bless.app.job;

import com.songbl.bless.common.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;



@Component
public class ScheduleUtils {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private Scheduler scheduler;

    /**
     * 创建定时任务
     */
    public void createScheduleJob(Date data,AcceptPersn persn) {
        System.out.println(persn.toString());
        logger.error("创建定时任务");
        try {
            scheduler.clear();
        } catch (SchedulerException e) {
            System.out.println("清除失败");
            logger.error("清除任务失败");
            e.printStackTrace();
        }
        try {
            // define the job and tie it to our DumbJob class
            logger.error("try1");
            JobDetail jobDetail = newJob(BlessJob.class)
                    .withIdentity("blessJob", "group1") // name "myJob", group "group1"
                    .usingJobData("to", persn.getTo())
                    .usingJobData("subject", persn.getSubject())
                    .usingJobData("content" , persn.getContent())
                    .build();

            //触发器
            logger.error("try2");
            SimpleTrigger trigger = (SimpleTrigger) newTrigger()
                    .withIdentity("trigger1", "group1")
                    .startAt(data) // some Date
                    .forJob("blessJob", "group1") // identify job with name, group strings
                    .build();

            //放入参数，运行时的方法可以获取（名字一定，值是实体）
//            jobDetail.getJobDataMap().put("to", "791243928@qq.com");

            //调度容器设置JobDetail和Trigger
            logger.error("try3");
            scheduler.scheduleJob(jobDetail, trigger);


        } catch (SchedulerException e) {
            logger.error("失败");
            logger.error(e.getMessage());
            System.out.println(e.toString());
            System.out.println(e.getMessage());
            throw new RRException("创建定时任务失败", e);
        }
    }


}
